﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PARK
{
    public class DateUt
    {
        /// <summary>
        /// 【毫秒级】获取时间（北京时间）
        /// </summary>
        /// <param name="timestamp">10位时间戳</param>
        public DateTime GetDateTimeMilliseconds(long timestamp)
        {
            long begtime = timestamp * 10000;
            DateTime dt_1970 = new DateTime(1970, 1, 1, 8, 0, 0);
            long tricks_1970 = dt_1970.Ticks;//1970年1月1日刻度
            long time_tricks = tricks_1970 + begtime;//日志日期刻度
            DateTime dt = new DateTime(time_tricks);//转化为DateTime
            return dt;
        }
        /// <summary>
        /// UTC时间戳Timestamp转换为北京时间
        /// </summary>
        /// <param name="timestamp">要转换的时间戳</param>
        /// <returns></returns>
        public DateTime GetDateTime(long timestamp)
        {
            //使用上面的方式会显示TimeZone已过时
            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            long lTime = long.Parse(timestamp + "0000000");
            TimeSpan timeSpan = new TimeSpan(lTime);
            DateTime targetDt = dtStart.Add(timeSpan).AddHours(8);
            return targetDt;
        }

        /// <summary>
        /// 时间格式化 传入的秒
        /// </summary>
        /// <param name="totalTime">秒</param>
        /// <returns>返回 00:00:00.00  时:分:秒</returns>
        public static string FormatTimescds(int totalTime)
        {
            var seconds = (int)(totalTime % 60);
            var minutes = (int)(totalTime / 60) % 60;
            var hours = (int)(totalTime / 3600) % 60;
            return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
        }
        /// <summary>
        /// 时间格式化 传入的毫秒
        /// </summary>
        /// <param name="totalTime">毫秒</param>
        /// <returns>返回 00:00.00  分:秒.毫秒</returns>
        public static string FormatTimemilliscds(int totalTime)
        {
            var milliseconds = (int)(totalTime % 1000);
            if (milliseconds.ToString().Length > 2)
            {
                milliseconds = Convert.ToInt32(milliseconds.ToString().Substring(0, 2));
            }
            var seconds = (int)((totalTime / 1000) % 60);
            var minutes = (int)((totalTime / 1000) / 60) % 60;
            return string.Format("{0:00}:{1:00}.{2}", minutes, seconds, milliseconds);
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GenerateRandomDigits(int length)
        {
            Random random = new Random();
            // 使用PadLeft配合长度和'0'字符来确保生成的数字字符串是指定长度
            return new string(Enumerable.Repeat('0', length).Select(x => (char)(random.Next(10) + '0')).ToArray());
        }
    }
}
